// pages/cart/index.js
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    orderList: [],
    currPrice: 0,
    totalNum: 0,
    isLogin: true,
    isChecked: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCartList();
  },

  getCartList() {
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo === '') {
      this.setData({
        isLogin: false,
      });
      return;
    } else {
      this.setData({
        isLogin: true,
      });
    }
    wx.cloud
      .callFunction({
        name: 'cart',
        data: {
          // 云函数方法
          type: 'getCartList',
          openid: userInfo.openid,
        },
      })
      .then((res) => {
        const list = res.result.data;
        this.setData({
          cartList: list,
        });
      })
      .catch((err) => {
        console.log('获取失败，', err);
      });
  },
  go2Details(e) {
    const { goodsid } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '../goods_detail/index?id=' + goodsid,
    });
  },
  getData(e, type) {
    const { id } = e.currentTarget.dataset;
    let { cartList, currPrice, totalNum } = this.data;
    const index = cartList.findIndex((val) => val.goods_id === id);
    const goods = cartList[index];
    const currNum = goods.num;
    let tempNum = currNum;
    let tempPrice = currPrice;

    if (type === 1) {
      tempNum++;
      if (goods.isChecked) {
        tempPrice = currPrice + goods.goods_price * (tempNum - currNum);
        totalNum++;
      }
    }
    if (type === -1) {
      tempNum--;
      if (goods.isChecked) {
        tempPrice = currPrice + goods.goods_price * (tempNum - currNum);
        totalNum--;
      }
    }
    goods.num = tempNum;

    return {
      id,
      cartList,
      index,
      goods,
      currNum,
      tempNum,
      totalNum,
      currPrice,
      tempPrice,
    };
  },
  subNum(e) {
    // 获取数据
    let { id, cartList, tempNum, tempPrice, totalNum } = this.getData(e, -1);
    // 修改数据
    this.setLatestData(cartList, tempPrice, id, tempNum, totalNum);
  },
  addNum(e) {
    // 获取数据
    let { id, cartList, tempNum, tempPrice, totalNum } = this.getData(e, 1);
    // 修改数据
    this.setLatestData(cartList, tempPrice, id, tempNum, totalNum);
  },
  setLatestData(cartList, tempPrice, id, tempNum, totalNum) {
    // 修改页面数据
    this.setData({
      cartList,
      totalNum,
      currPrice: tempPrice,
    });
    // 修改云数据库数据
    wx.cloud
      .callFunction({
        name: 'cart',
        data: {
          type: 'updCart',
          id: id,
          from: 'cart',
          num: tempNum,
        },
      })
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });
  },
  handleChange(e) {
    const { value } = e.detail;
    let { cartList, totalNum } = this.data;
    const valLen = value.length,
      listLen = cartList.length;
    let total = 0;
    let isCheckedNum = 0;
    let currNum = 0;
    for (let i = 0; i < listLen; i++) {
      if (cartList[i].num !== 0) {
        isCheckedNum++;
      }
      cartList[i].isChecked = false;
      for (let j = 0; j < valLen; j++) {
        if (cartList[i]._id === value[j]) {
          cartList[i].isChecked = true;
          total = total + cartList[i].goods_price * cartList[i].num;
          currNum += cartList[i].num;
          break;
        }
      }
    }
    let { isChecked } = this.data;
    isChecked = valLen !== isCheckedNum ? false : true;
    this.setData({
      cartList,
      currPrice: total,
      totalNum: currNum,
      isChecked,
    });
  },
  handleAllSelect() {
    let { cartList, isChecked, totalNum } = this.data;
    let total = 0;
    if (!isChecked) {
      cartList.forEach((val) => {
        if (val.num !== 0 && !val.isBuyed) {
          val.isChecked = true;
          total += val.goods_price * val.num;
          totalNum += val.num;
        }
      });
    } else {
      cartList.forEach((val) => (val.isChecked = false));
      totalNum = 0;
    }
    this.setData({
      cartList,
      isChecked: !isChecked,
      currPrice: total,
      totalNum,
    });
  },
  pay() {
    let { cartList, orderList } = this.data;
    for (let i = 0; i < cartList.length; i++) {
      let item = cartList[i];
      if (item.isChecked) {
        orderList.push(item);
        item.isBuyed = true;
        wx.cloud.callFunction({
          name: 'cart',
          data: {
            type: 'updCart',
            id: cartList[i].goods_id,
            from: 'cartPay',
          },
        });
      }
    }
    this.setData({
      cartList,
      orderList,
    });
    const that = this;
    wx.navigateTo({
      url: '../pay/index',
      success: function (res) {
        res.eventChannel.emit('acceptData', { orderList });
      },
      complete: function () {
        that.setData({
          orderList: [],
        });
      },
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCartList();
    this.setData({
      totalNum: 0,
      isChecked: false,
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 100,
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.getCartList();
    this.setData({
      currPrice: 0,
      isShow: true,
      isLogin: true,
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
